package com.jinkeen.xiaxie.qrCode

import android.graphics.Bitmap
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.MultiFormatWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import com.jinkeen.xiaxie.R
import java.util.*

class QrCodeActivity : AppCompatActivity() {
    private lateinit var btnCreate: Button
    private lateinit var etContent: EditText
    private lateinit var qrCodeImage: ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_qr_code)
        btnCreate = findViewById(R.id.btn_create)
        etContent = findViewById(R.id.et_content)
        qrCodeImage = findViewById(R.id.image_qr)
        btnCreate.setOnClickListener {
            if (etContent.text.toString().isNotEmpty()) {
//                val write=MultiFormatWriter()
                val bitmap = createQRCodeBitmap(etContent.text.toString(), 60)
                qrCodeImage.setImageBitmap(bitmap)
            }
        }
    }

    private fun createQRCodeBitmap(str: String, size: Int): Bitmap? {
        val qrParam = Hashtable<EncodeHintType, Any>()
        //设置QR二维码的纠错级别
        qrParam[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.H
//        编码方式
        qrParam[EncodeHintType.CHARACTER_SET] = "UTF-8"
        //生成的QR二维码数据--这里只是得到一个由true和false组成的数组
        //参数顺序分别为 编码内容 编码类型 生成图片宽高 设置参数
        try {
            val bitMatrix =
                MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, size, size, qrParam)
            //利用二维码数据创建bitmap图片,分别设为黑白两色
            val w = bitMatrix.width
            val h = bitMatrix.height
            val data = IntArray(w * h)
            for (y in 0 until h) {
                for (x in 0 until w) {
                    if (bitMatrix[x, y]) data[y * w + x] = -0x1000000 // 黑色
                    else data[y * w + x] = 0x00ffffff // -1 相当于0xffffffff 白色
                }
            }
            //创建一张bitmap图片
            val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
            //将上面的二维码颜色数组传入,生成图片颜色
            bitmap.setPixels(data, 0, w, 0, 0, w, h)
            return bitmap
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }
}